import "babel-polyfill";
import RBTree from "./rbtree";

export var OrderedMapTemplate = function(compare = (x, y) => x.key - y.key) {
    return class {
        tree = new (RBTree(compare))();

        constructor() {
            for (let x of arguments) {
                this.set(x.key, x.value);
            }
        }

        get [Symbol.toStringTag]() {
            return "OrderedMap";
        }

        get size() {
            return this.tree.size;
        }

        *[Symbol.iterator](direction = 1) {
            yield* this.tree[Symbol.iterator](direction);
        }

        has(key) {
            return this.tree.has({key});
        }
        get(key) {
            var node = this.tree.find({key});
            return node && node.data.value;
        }
        set(key, value) {
            var node = this.tree.find({key});
            if (node) {
                node.data.value = value;
            } else {
                this.tree.add({key, value});
            }
            return value;
        }
        delete(key) {
            return this.tree.delete({key});
        }
    };
};

export default OrderedMapTemplate();
